package com.sjtu.network.chatanalysis.service

import org.springframework.beans.factory.InitializingBean
import org.springframework.stereotype.Service
import kotlin.concurrent.timer

@Service
class ScoreService: InitializingBean {
    private lateinit var sequenceGenerator: SequenceGenerator

    override fun afterPropertiesSet() {
        sequenceGenerator = SequenceGenerator(listOf(5, 8, 6, 10), 5)
    }

    fun score(content: String): Int {
        return sequenceGenerator.processInput(content)
    }

}

class SequenceGenerator(private val sequence: List<Int>, private val timeoutMinutes: Long) {
    private var currentIndex = 0
    private var lastInputTime = System.currentTimeMillis()

    init {
        startTimer()
    }

    fun processInput(input: String): Int {
        // 每次收到输入时更新最后输入时间
        lastInputTime = System.currentTimeMillis()

        return when (input) {
            "reset" -> {
                reset()
                sequence[currentIndex]
            }
            else -> {
                sequence[currentIndex].also {
                    // 更新 currentIndex，如果超出序列范围则重置为 0
                    currentIndex = (currentIndex + 1) % sequence.size
                }
            }
        }
    }

    private fun reset() {
        currentIndex = 0
    }

    private fun startTimer() {
        val timer = timer(period = 1000) {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastInputTime >= timeoutMinutes * 60 * 1000) {
                // 如果超过设定的时间没有输入，则重置序列
                reset()
            }
        }
    }
}